package com.mzkj.wanjulaile.mobile.api.modules.order.service;

import com.mzkj.common.data.StatusCode;
import com.mzkj.common.utils.Collections3;
import com.mzkj.common.utils.DateUtils;
import com.mzkj.common.utils.StringUtils;
import com.mzkj.wanjulaile.mobile.api.common.entity.ResultEntity;
import com.mzkj.wanjulaile.mobile.api.common.service.ServiceException;
import com.mzkj.wanjulaile.mobile.api.modules.account.entity.Account;
import com.mzkj.wanjulaile.mobile.api.modules.account.mapper.AccountMapper;
import com.mzkj.wanjulaile.mobile.api.modules.account.mapper.BuyVipMapper;
import com.mzkj.wanjulaile.mobile.api.modules.coupon.entity.AccountCoupon;
import com.mzkj.wanjulaile.mobile.api.modules.coupon.mapper.AccountCouponMapper;
import com.mzkj.wanjulaile.mobile.api.modules.coupon.mapper.InviteMapper;
import com.mzkj.wanjulaile.mobile.api.modules.order.constant.Constant;
import com.mzkj.wanjulaile.mobile.api.modules.order.entity.Order;
import com.mzkj.wanjulaile.mobile.api.modules.order.entity.OrderToy;
import com.mzkj.wanjulaile.mobile.api.modules.order.mapper.OrderMapper;
import com.mzkj.wanjulaile.mobile.api.modules.stock.entity.Stock;
import com.mzkj.wanjulaile.mobile.api.modules.stock.mapper.StockMapper;
import com.mzkj.wanjulaile.mobile.api.modules.weChat.entity.NotifyReturnData;
import com.mzkj.wanjulaile.mobile.api.modules.weChat.entity.WxConstant;
import com.mzkj.wanjulaile.mobile.api.modules.weChat.service.NotifyReturnService;
import com.mzkj.wanjulaile.mobile.api.modules.weChat.service.WechatPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;


@Service
@Transactional(readOnly = true)
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderToyService orderToyService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private BuyVipMapper buyVipMapper;
    @Autowired
    private AccountCouponMapper accountCouponMapper;
    @Value("${orderTimeOut}")
    private int orderTimeOut;
    @Autowired
    private WechatPayService wechatPayService;
    @Autowired
    private NotifyReturnService notifyReturnService;
    @Autowired
    private InviteMapper inviteMapper;

    public Order get(String id) {
        Order order = orderMapper.get(id);
        order.setOrderToys(orderToyService.getListByOrderId(id));
        return order;
    }

    public List<Order> findList(Order order) {
        return orderMapper.findList(order);
    }

    @Transactional(readOnly = false)
    public void save(Order order) {
        if (StringUtils.isBlank(order.getId())) {
            order.setIsNewRecord(true);
            order.preInsert();
            orderMapper.insert(order);
        } else {
            order.preUpdate();
            orderMapper.update(order);
        }
    }

    @Transactional(readOnly = false)
    public void delete(Order order) {
        orderMapper.delete(order);
    }

    public Order getByOrderNumber(String orderNumber) {
        return orderMapper.getByOrderNumber(orderNumber);
    }

    @Transactional
    public int updatePayStatus(Order order) {
        return orderMapper.updatePayStatus(order);
    }

    @Override
    public Order get(Order entity) {
        return orderMapper.get(entity);
    }

    /**
     * 修改订单状态 后续添加同时刻的其他逻辑操作
     *
     * @param order
     */
    @Transactional(readOnly = false)
    public void updateStatus(Order order) {
        try {
            order.preUpdate();
            List<OrderToy> orderToys = orderToyService.getListByOrderId(order.getId());
            //取消订单 更新库存
            if (order.getStatus().equals(Constant.ORDER_CANCEL)) {
                //还原库存数量
                if (!Collections3.isEmpty(orderToys)) {
                    for (OrderToy orderToy : orderToys) {
                        if (orderToy.getToyStatus().equals(Constant.ORDER_TOY_SHIPPING)) {
                            Stock stock = stockMapper.getByToyId(orderToy.getToy().getId());
                            stock.setRealCount(stock.getRealCount() + orderToy.getToyCount());
                            stockMapper.update(stock);
                        }
                    }
                }
                //查找非取消的订单只有一个
                Order temp = orderMapper.get(order);
                List<Order> orderList = orderMapper.findPayedOrderListByAccountId(temp.getAccount().getId());
                if (orderList.size() == 1) {
                    //第一次取消订单重置时效为空
                    Account account = accountMapper.get(temp.getAccount());
                    accountMapper.setNullVipTime(account);
                    Account account1 = accountMapper.get(account);
                    buyVipMapper.resetStatus(account1.getId());
                    inviteMapper.resetInviteTimeUse(account1.getId());
                }
                //更新支付状态,如果是已付款退款
                if (temp.getPayStatus().equals(Constant.PAYSTATUS_PAID)) {
                    //优惠券==运费 已退款
                    if (temp.getShipFee() - (temp.getCouponVal() == null ? 0 : temp.getCouponVal()) == 0){
                        order.setPayStatus(Constant.PAYSTATUS_RETURNED);
                    }else{
                        order.setPayStatus(Constant.PAYSTATUS_REFUND_PROCESSING);
                    }
                    order.setCancelDate(new Date());
                }
                if(temp.getAccountCoupon()!=null&&!StringUtils.isEmpty(temp.getAccountCoupon().getId())){
                    //退还优惠券
                    AccountCoupon accountCoupon=accountCouponMapper.get(temp.getAccountCoupon().getId());
                    accountCoupon.setCount(accountCoupon.getCount()+1);
                    accountCoupon.setDelFlag("0");
                    accountCoupon.setUpdateDate(new Date());
                    accountCouponMapper.update(accountCoupon);
                }

            }
            orderMapper.update(order);
            Order order1 = orderMapper.get(order);
            // 取消且申请退款中 立即退款
            if (null != order1 && order1.getPayStatus().equals(Constant.PAYSTATUS_REFUND_PROCESSING) && order1.getStatus().equals(Constant.ORDER_CANCEL)){
                ResultEntity<NotifyReturnData> resultMessage = wxRefund(order1);
                NotifyReturnData notifyReturnData = resultMessage.getData();
                //申请退款成功立即执行一次同步退款状态操作
                if("0".equals(resultMessage.getStatusCode())) {
                    wechatPayService.syncRefundStatus(notifyReturnData);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("订单操作异常,请稍后再试");
        }
    }

    @Transactional
    public ResultEntity<NotifyReturnData> wxRefund(Order order) {
        ResultEntity<NotifyReturnData> resultMessage = new ResultEntity<>();
        try {
            NotifyReturnData returnData = wechatPayService.refund(order.getOrderNumber(), null,"order");
            //申请退款成功
            if (null != returnData && WxConstant.RETURN_SUCCESS.equals(returnData.getReturn_code())) {
                if (WxConstant.RESULT_SUCCESS.equals(returnData.getResult_code())) {
                    //订单退款批次号
                    Order temp = getByOrderNumber(returnData.getOut_trade_no());
                    if (null != temp) {
                        temp.setBatchNo(returnData.getOut_refund_no());//退款单号
                        save(temp);
                        //记录退款日志
                        returnData.setType(Constant.NOTIFY_TYPE_REFUND);
                        notifyReturnService.insert(returnData);
                    }
                    resultMessage.setStatusCode("0");
                    resultMessage.setMsg("申请微信退款成功");
                    resultMessage.setData(returnData);
                } else {
                    resultMessage.setStatusCode("4000");
                    resultMessage.setMsg(returnData.getErr_code_des());
                }
            } else if (null != returnData) {
                resultMessage.setStatusCode("4001");
                resultMessage.setMsg(returnData.getReturn_msg());
            } else {
                resultMessage.setStatusCode("4002");
                resultMessage.setMsg("不存在该已支付订单");
            }
        } catch (Exception e) {
            resultMessage.setStatusCode("4003");
            resultMessage.setMsg("申请微信退款异常");
            throw new ServiceException("申请微信退款异常", e);
        }
        return resultMessage;
    }

    /**
     * 查询上次订单
     * 上一次订单 非取消 已支付
     *
     * @param accountId
     * @return
     */
    public Order getLastOrderByAccountId(String accountId) {
        return orderMapper.getLastOrderByAccountId(accountId);
    }

    /**
     * 根据账号获取订单列表
     *
     * @param accountId
     * @return
     */
    public List<Order> findListByAccountId(String accountId) {
        List<Order> orderList = orderMapper.findListByAccountId(accountId);
        if (!Collections3.isEmpty(orderList)) {
            for (Order temp : orderList) {
                temp.setOrderToys(orderToyService.getListByOrderId(temp.getId()));
            }
        }
        return orderList;
    }


    /**
     * 上一次订单 非取消订单
     *
     * @param accountId
     * @return
     */
    public Order getLastOrderByAccountId2(String accountId) {
        return orderMapper.getLastOrderByAccountId2(accountId);
    }

    /**
     * 上上次订单
     *
     * @param accountId
     * @return
     */
    public Order getLastOrder2ByAccountId(String accountId) {
        return orderMapper.getLastOrder2ByAccountId(accountId);
    }

    @Transactional
    public ResultEntity<Map> validateOrderStatus(Order order, ResultEntity<Map> resultMessage) {
        if (order.getStatus().equals(Constant.ORDER_CANCEL)) {
            resultMessage.setStatusCode(StatusCode.SC400105.getValue());
            resultMessage.setMsg(StatusCode.SC400105.getDesc());
        } else if (DateUtils.pastMinutes(order.getCreateDate()) >= orderTimeOut) {
            //超过时限分钟 取消订单
            order.setStatus(Constant.ORDER_CANCEL);
            updateStatus(order);
            resultMessage.setStatusCode(StatusCode.SC400106.getValue());
            resultMessage.setMsg(StatusCode.SC400106.getDesc());
        } else {
            resultMessage.setStatusCode(StatusCode.SC0.getValue());
            resultMessage.setMsg(StatusCode.SC0.getDesc());
        }
        return resultMessage;
    }

    /**
     * 查找用户最后一次的订单  退押金用
     * @param accountId
     * @return
     */
    public Order findLastOrderByAccountId(String accountId) {
        return orderMapper.findLastOrderByAccountId(accountId);
    }


}